from django.shortcuts import render, redirect
from app01 import models
from django import forms
# 验证方式1：引入对模型的正则表达式
from django.core.validators import RegexValidator
# 验证方式2
from django.core.exceptions import ValidationError
# 后端代码安全标记到前端
from django.utils.safestring import mark_safe


class PrettyModelForm(forms.ModelForm):
    # 使用bootstrap样式
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    # 验证方式1：正则表达式
    # mobile = forms.CharField(
    #     label="手机号",
    #     validators=[RegexValidator(r'[3-9]\d{9}$','手机号格式错误')],#\d{11}#1[3-9]\d{9}$
    # )

    # 获取模板元包
    class Meta:
        model = models.PrettyNum
        # 获取字段
        # fields = "__all__"#获取全部字段
        # exclude = ["level"]#反选指定字段
        fields = ["mobile", "price", "level", "status"]  # 获取指定字段

    # 验证方式2：钩子函数
    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]
        # 验证手机号是否已存在
        exists = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号已存在")
        elif len(txt_mobile) != 11:
            raise ValidationError("手机号格式错误")
        return txt_mobile


class PrettyEditModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    mobile = forms.CharField(disabled=True, label="手机号")
    # 验证方式1：正则表达式
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'[3-9]\d{9}$', '手机号格式错误')],  # \d{11}#1[3-9]\d{9}$
    )

    class Meta:
        model = models.PrettyNum
        fields = ["mobile", "price", "level", "status"]

    def clean_mobile(self):
        # 当前编辑的那一行主键（id）
        # print(self.instance.pk)
        txt_mobile = self.cleaned_data["mobile"]
        # 验证手机号是否已存在(排除自身)
        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号已存在")
        elif len(txt_mobile) != 11:
            raise ValidationError("手机号格式错误")
        return txt_mobile


def pretty_list(request):
    """靓号列表"""
    # for i in range(100):
    #     models.PrettyNum.objects.create(mobile="12332112311",price=10,level=1,status=1)

    # 搜索字典
    data_dict = {}
    value = request.GET.get("q", "")
    if value:
        data_dict["mobile__contains"] = value
    # 获取的列表按等级降序排列
    # select * from 表 order by level desc;
    # qureyset = models.PrettyNum.objects.all().order_by("-level")
    # 分页功能
    # 根据用户访问页码计算起始位置
    page = int(request.GET.get("page", 1))
    page_size = 10
    start = (page - 1) * page_size
    end = page * page_size

    qureyset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")[start:end]
    # 生成页码代码
    """
                <li><a href="?page=1">1</a></li>
                <li><a href="?page=2">2</a></li>
                <li><a href="?page=3">3</a></li>
                <li><a href="?page=4">4</a></li>
                <li><a href="?page=5">5</a></li>
                ……
    """
    # 获取数据库中的数据条数
    total_count = models.PrettyNum.objects.filter(**data_dict).order_by("-level").count()
    # 总页数
    total_page_count, div = divmod(total_count, page_size)  # divmod除法函数，返回值：商，余数
    if div:
        total_page_count += 1
    # 设置按钮显示范围
    plus = 5
    if total_page_count <= 2 * plus + 1:
        start_page = 1
        end_page = total_page_coun + 1
    else:
        # 当前页小于5
        if page <= plus:
            start_page = 1
            end_page = 2 * plus + 1
        else:
            if (page + plus) > total_page_count:
                start_page = total_page_count - 2 * plus
                end_page = total_page_count
            else:
                start_page = page - plus
                end_page = page + plus + 1

    # 页码列表
    page_str_list = []
    # 首页
    page_str_list.append('<li><a href="?page={}">首页</a></li>'.format(1))
    # 上一页
    if page > 1:
        prev = '<li><a href="?page={}">上一页</a></li>'.format(page - 1)
    else:
        prev = '<li><a href="?page={}">上一页</a></li>'.format(1)
    page_str_list.append(prev)
    # 页码
    for i in range(start_page, end_page):  # range前取后不取，所以还要加一
        if i == page:  # 当前页显示按钮样式
            ele = '<li class="active"><a href="?page={}">{}</a></li>'.format(i, i)
        else:
            ele = '<li><a href="?page={}">{}</a></li>'.format(i, i)
        page_str_list.append(ele)
    # 下一页
    if page < total_page_count:
        prev = '<li><a href="?page={}">下一页</a></li>'.format(page + 1)
    else:
        prev = '<li><a href="?page={}">下一页</a></li>'.format(total_page_count)
    page_str_list.append(prev)
    # 尾页
    page_str_list.append('<li><a href="?page={}">尾页</a></li>'.format(total_page_count))
    # 输入框
    search_string = """
        <li>
                    <!--输入框组件-->
                    <form style="float: left;margin-left: -1px" method="get">
                            <input name="page"
                                   style="position: relative;float: left;display: inline-block;width: 80px;border-radius: 0;"
                                   type="text" class="form-control" placeholder="页码">
                            <button style="border-radius: 0" class="btn btn-default" type="submit">跳转</button>
                    </form>
                </li>
    """
    page_str_list.append(search_string)
    page_string = mark_safe("".join(page_str_list))
    return render(request, "pretty_list.html", {"qureyset": qureyset, "value": value, "page_string": page_string})


def pretty_add(request):
    """添加靓号"""
    if request.method == "GET":
        form = PrettyModelForm()
        return render(request, 'pretty_add.html', {"form": form})
    form = PrettyModelForm(data=request.POST)
    if form.is_valid():  # 校验成功
        form.save()
        return redirect("/pretty/list/")
    return render(request, 'pretty_add.html', {'form': form})


def pretty_edit(request, nid):
    """编辑靓号"""
    # 获取当前行数据
    row_object = models.PrettyNum.objects.filter(id=nid).first()
    if request.method == "GET":
        # 将默认值传递给页面
        form = PrettyEditModelForm(instance=row_object)
        return render(request, 'pretty_edit.html', {"form": form})
    # 处理post请求
    form = PrettyEditModelForm(data=request.POST, instance=row_object)
    # 校验
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")
    return render(request, 'pretty_edit.html', {"form": form})


def pretty_delete(request):
    """删除靓号"""
    nid = request.GET.get("nid")
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect("/pretty/list/")
